package com.tbit.main.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tbit.common.constant.PerformanceTypeConstant;
import com.tbit.common.entity.view.PageResult;
import com.tbit.main.constant.AccountConfigExtConstant;
import com.tbit.main.constant.enums.PerformanceBizType;
import com.tbit.main.constant.enums.PerformanceRuleType;
import com.tbit.main.dao.core.AccountUserDao;
import com.tbit.main.dao.log.PowerChangeLogDao;
import com.tbit.main.dao.log.PowerChangePerformanceDao;
import com.tbit.main.h2.pojo.ParkPoint;
import com.tbit.main.pojo.*;
import com.tbit.main.pojo.maintain_performance.Range;
import com.tbit.main.pojo.maintain_performance.config.PowerChangePerformanceConfig;
import com.tbit.main.pojo.maintain_performance.constant.RuleTypeConstant;
import com.tbit.main.pojo.maintain_performance.group.IntervalAndValidityBasedGroup;
import com.tbit.main.pojo.maintain_performance.rule.*;
import com.tbit.main.pojo.maintain_performance.stat.*;
import com.tbit.main.service.AccountConfigExtService;
import com.tbit.main.service.MachineService;
import com.tbit.main.service.ParkPointService;
import com.tbit.main.service.RedisService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author <a href="mailto:zheng.zebiao@tbit.com.cn">zb</a>
 * @since 2025/3/4
 */
@Slf4j
@Service
@AllArgsConstructor
public class PowerChangePerformanceService extends ServiceImpl<PowerChangePerformanceDao, PowerChangePerformance> {
    final AccountUserDao accountUserDao;
    final RedisService redisService;
    final MachineService machineService;
    final AccountConfigExtService configExtService;
    final ParkPointService parkPointService;
    final PerformanceRuleGroupService ruleGroupService;
    final PowerChangeLogDao powerChangeLogDao;
    final PowerChangePerformanceLogService performanceLogService;

    /**
     * 分页查询详情
     */
    public PageResult<PowerChangePerformanceDetail> queryDetailPage(PerformanceDetailReq req) {
        // 查询绩效分页
        Page<PowerChangePerformanceDetail> details = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        getBaseMapper().queryDetailPage(req);
        details.close();

        if (CollUtil.isNotEmpty(details)) {
            String accountUserIds = details.getResult().stream()
                    .map(PowerChangePerformanceDetail::getAccountUserId)
                    .map(String::valueOf)
                    .collect(Collectors.joining(","));
            Map<Integer, AccountUser> accountUserMap = Optional.ofNullable(accountUserDao.getByIds(accountUserIds))
                    .map(x -> x.stream()
                            .collect(Collectors.toMap(AccountUser::getAccountUserId, Function.identity()))
                    )
                    .orElse(Collections.emptyMap());

            for (PowerChangePerformanceDetail detail : details) {
                // 补充运维人员信息
                AccountUser accountUser = accountUserMap.get(detail.getAccountUserId());
                if (accountUser != null) {
                    detail.setAccountUserName(accountUser.getName());
                    detail.setAccountUserPhone(accountUser.getPhone());
                }
            }
        }

        return PageResult.convertPage(details.toPageInfo());
    }

    /**
     * 查询绩效统计
     *
     * @param req
     * @return
     */
    public PerformanceCountResp queryPerformanceCount(PerformanceCountReq req) {
        return getBaseMapper().queryPerformanceCount(req);
    }

    /**
     * 分页查询概览
     */
    public List<PerformanceOverviewResp> queryOverviewPage(PerformanceOverviewReq req,AccountUser loginAccountUser) {
        //getBaseMapper().queryOverviewPage(req);
        List<PerformanceOverviewResp> list = this.getPerformanceList(req, loginAccountUser);

        if (CollUtil.isNotEmpty(list)) {
            String accountUserIds = list.stream()
                    .map(PerformanceOverviewResp::getAccountUserId)
                    .map(String::valueOf)
                    .collect(Collectors.joining(","));
            Map<Integer, AccountUser> accountUserMap = Optional.ofNullable(accountUserDao.getByIds(accountUserIds))
                    .map(x -> x.stream()
                            .collect(Collectors.toMap(AccountUser::getAccountUserId, Function.identity()))
                    )
                    .orElse(Collections.emptyMap());
            for (PerformanceOverviewResp detail : list) {
                // 补充运维人员信息
                AccountUser accountUser = accountUserMap.get(detail.getAccountUserId());
                if (accountUser != null) {
                    detail.setAccountUserName(accountUser.getName());
                    detail.setAccountUserPhone(accountUser.getPhone());
                    detail.setDelFlag(accountUser.getDelFlag());
                }
            }
        }
        return list;
    }

    public static final String MACHINE_PARK_POINT_KEY = "maintainPerformance:powerChange:parkPoint:";

    /**
     * 缓存车辆当前所在站点，供后续换电绩效使用
     *
     * @param machineId 车辆id
     */
    public void cacheParkPoint(Integer machineId) {
        ParkMachine parkMachine = machineService.getParkId(machineId);
        if (parkMachine != null && Objects.equals(parkMachine.getInside(), 1)) {
            redisService.add(MACHINE_PARK_POINT_KEY + machineId, parkMachine.getParkPointId().toString(), 7, TimeUnit.DAYS);
        }else {
            redisService.del(MACHINE_PARK_POINT_KEY + machineId);
        }
    }

    /**
     * 获取车辆当前所在站点
     *
     * @param machineId 车辆id
     * @return 所在站点id
     */
    public Integer getParkPointCache(Integer machineId) {
        String parkPointId = redisService.get(MACHINE_PARK_POINT_KEY + machineId);
        if (parkPointId != null) {
            return Integer.parseInt(parkPointId);
        }
        return null;
    }

    /**
     * 计算并插入绩效
     *
     * @param pcl 换电记录
     */
    public void calculateAndInsertPerformance(PowerChangeLog pcl) {
        try {
            // 非有效记录，不计算绩效
            if (!Objects.equals(pcl.getIsValid(), 1)) {
                return;
            }

            // 检查开关
            AccountConfigExt performanceSwitch = configExtService.getParamKey(pcl.getAccountId(), AccountConfigExtConstant.POWER_CHANGE_PERFORMANCE);
            if (performanceSwitch == null || Objects.equals(performanceSwitch.getParamValue(), "0")) {
                return;
            }

            PowerChangePerformance pcp = getOne(Wrappers.<PowerChangePerformance>query()
                    .eq(PowerChangePerformance.Fields.powerChangeLogId, pcl.getPowerChangeLogId())
            );
            if (pcp != null) {
                log.info("[换电绩效] 已有记录,不处理。 换电记录id: {}, 绩效记录id: {}", pcl.getPowerChangeLogId(), pcp.getPerformanceId());
                return;
            }
            // 生成新绩效记录
            log.info("[换电绩效] 生成新绩效记录, 换电记录id: {}", pcl.getPowerChangeLogId());
            pcp = new PowerChangePerformance();
            pcp.setPowerChangeLogId(pcl.getPowerChangeLogId());
            pcp.setOrderCountAfterChange(0);
            pcp.setAccountId(pcl.getAccountId());

            // 缓存取站点
            // 如果换电后首单时效过长（7天）则无法获取到站点信息
            Integer parkPointId = getParkPointCache(pcl.getMachineId());
            if (parkPointId != null) {
                ParkPoint parkPoint = parkPointService.getByParkPointId(parkPointId);
                if (parkPoint != null) {
                    pcp.setParkId(parkPoint.getParkPointId());
                    pcp.setParkName(parkPoint.getName());
                }
            }

            // 计算绩效
            List<PowerChangePerformanceLog> performanceLogs = new ArrayList<>();
            switch (performanceSwitch.getParamValue()) {
                case "1":
                    calculateConventionModePerformance(pcl, pcp, performanceLogs);
                    break;
                case "2":
                    calculateStationModePerformance(pcp, performanceLogs);
                    break;
            }

            // 绩效记录入库
            save(pcp);
            // 保存绩效日志
            if (!performanceLogs.isEmpty()) {
                // 填充绩效记录id
                PowerChangePerformance finalPcp = pcp;
                performanceLogs.forEach(performanceLog -> performanceLog.setPerformanceId(finalPcp.getPerformanceId()));
                performanceLogService.insertBatch(performanceLogs);
            }
        } catch (Exception e) {
            log.error("[换电绩效] 计算绩效时发生错误, 换电记录id: {}", pcl.getPowerChangeLogId(), e);
        }
    }

    /**
     * 根据车辆id更新7天内最近一次换电绩效
     *
     * @param machineId 车辆id
     * @param orderNO   订单编号
     */
    public void updatePerformanceByNewOrder(Integer machineId, String orderNO) {
        PowerChangeLog pcl = powerChangeLogDao.selectLast7DayFirstValid(machineId);
        if (pcl == null) {
            return;
        }

        // 检查开关
        AccountConfigExt performanceSwitch = configExtService.getParamKey(pcl.getAccountId(), AccountConfigExtConstant.POWER_CHANGE_PERFORMANCE);
        if (performanceSwitch == null || !Objects.equals(performanceSwitch.getParamValue(), "1")) {
            return;
        }

        try {
            // 获取常规配置
            PowerChangePerformanceConfig config = ruleGroupService.selectBizPerformanceConfig(pcl.getAccountId(), PowerChangePerformanceConfig::fromRaw, PerformanceBizType.POWER_CHANGE_CONVENTION);
            if ((config.getIntervalAndValidityBased() == null || !config.getIntervalAndValidityBased().getEnabled())) {
                return;
            }

            PowerChangePerformance pcp = getOne(Wrappers.<PowerChangePerformance>query()
                    .eq(PowerChangePerformance.Fields.powerChangeLogId, pcl.getPowerChangeLogId())
            );
            if (pcp == null || Objects.equals(pcp.getPerformanceType(), PerformanceTypeConstant.MANUAL)) {
                log.info("[换电绩效] 换电记录id: {}, 绩效不存在或者是手动绩效,不处理。", pcl.getPowerChangeLogId());
                return;
            }

            // 产生订单时效/时段
            LocalDateTime changeTime = DateUtil.parseLocalDateTime(pcl.getChangeTime());
            LocalDateTime orderTime = LocalDateTime.now();
            LocalTime changeLocalTime = changeTime.toLocalTime();

            BigDecimal performance = pcp.getPerformance();
            StringBuilder detail = new StringBuilder(pcp.getPerformanceDetail());

            // 换电时间是否在时段、时效规则区间内
            IntervalAndValidityBasedGroup intervalAndValidityBasedGroup = config.getIntervalAndValidityBased();
            // 判断是否超过最大订单数限制 是否开启该规则
            if (intervalAndValidityBasedGroup != null
                    && intervalAndValidityBasedGroup.getEnabled()
                    && (intervalAndValidityBasedGroup.getMaxOrderCount() > pcp.getOrderCountAfterChange())) {
                List<PowerChangePerformanceLog> performanceLogs = new ArrayList<>(1);
                List<IntervalAndValidityBasedRule> rules = intervalAndValidityBasedGroup.getRules();
                for (IntervalAndValidityBasedRule rule : rules) {
                    Range<String> completedDuration = rule.getCompletedDuration();
                    // completedDuration 转换为LocalTime去比较
                    LocalTime start = LocalTime.parse(completedDuration.getStart2Calc());
                    LocalTime end = LocalTime.parse(completedDuration.getEnd2Calc());
                    Range completedRange = new Range<LocalTime>();
                    completedRange.setStart(start);
                    completedRange.setEnd(end);
                    if (completedRange.match(changeLocalTime)) {
                        // 换电时间在此时间内
                        String ruleType = rule.getRuleType();
                        switch (ruleType) {
                            case RuleTypeConstant.INTERVAL_BASED_RULE:// 基于时间间隔的规则
                                IntervalAndValidityBasedSubRule subRule = rule.calculatePerformance(changeTime, orderTime);
                                if (subRule != null) {
                                    performance = performance.add(subRule.getPerformance());
                                    log.info("[换电绩效] 换电记录id: {}, 适用订单时段绩效, 时段: {}, 订单号: {}", pcp.getPowerChangeLogId(), subRule.getOrderIntervalOrHour(), orderNO);
                                    detail.append("产生订单时段绩效: ")
                                            .append(NumberUtil.toStr(subRule.getPerformance()))
                                            .append("(")
                                            .append(subRule.getOrderIntervalOrHour())
                                            .append(");");
                                    PowerChangePerformanceLog performanceLog = new PowerChangePerformanceLog();
                                    BeanUtil.copyProperties(pcp, performanceLog, "performance", "performanceDetail", "remark");
                                    performanceLog.setPerformance(subRule.getPerformance());
                                    performanceLog.setPerformanceDetail("产生订单时段绩效: " + NumberUtil.toStr(subRule.getPerformance()) + "(" + subRule.getOrderIntervalOrHour() + ");");
                                    performanceLog.setRuleType(PerformanceRuleType.INTERVAL.getValue());
                                    performanceLog.setFirstOrderTime((int) Duration.between(changeTime, orderTime).toMinutes());
                                    performanceLog.setOrderCountAfterChange(pcp.getOrderCountAfterChange() + 1);
                                    performanceLog.setRemark("MAIN-INTERVAL_BASED_RULE-产生订单时段");
                                    performanceLogs.add(performanceLog);
                                }
                                break;
                            case RuleTypeConstant.VALIDITY_BASED_RULE: //基于时效的规则
                                long hours = Duration.between(changeTime, orderTime).toHours();
                                IntervalAndValidityBasedSubRule subValidityBasedRule = rule.calculatePerformance((int) hours);
                                if (subValidityBasedRule != null) {
                                    performance = performance.add(subValidityBasedRule.getPerformance());
                                    log.info("[换电绩效] 换电记录id: {}, 适用订单时效绩效, 时效: {}h, 订单号: {}", pcp.getPowerChangeLogId(), subValidityBasedRule.getOrderIntervalOrHour(), orderNO);
                                    detail.append("产生订单时效绩效: ")
                                            .append(NumberUtil.toStr(subValidityBasedRule.getPerformance()))
                                            .append("(")
                                            .append(subValidityBasedRule.getOrderIntervalOrHour())
                                            .append("小时);");
                                    PowerChangePerformanceLog performanceLog = new PowerChangePerformanceLog();
                                    BeanUtil.copyProperties(pcp, performanceLog, "performance", "performanceDetail", "remark");
                                    performanceLog.setPerformance(subValidityBasedRule.getPerformance());
                                    performanceLog.setPerformanceDetail("产生订单时效绩效: " + NumberUtil.toStr(subValidityBasedRule.getPerformance()) + "(" + subValidityBasedRule.getOrderIntervalOrHour() + ");");
                                    performanceLog.setRuleType(PerformanceRuleType.VALIDITY.getValue());
                                    performanceLog.setFirstOrderTime((int) Duration.between(changeTime, orderTime).toMinutes());
                                    performanceLog.setOrderCountAfterChange(pcp.getOrderCountAfterChange() + 1);
                                    performanceLog.setRemark("MAIN-VALIDITY_BASED_RULE-产生订单时效");
                                    performanceLogs.add(performanceLog);
                                }
                                break;
                            default:
                                break;
                        }
                    }

                }
                // 保存绩效日志
                if (!performanceLogs.isEmpty()) {
                    performanceLogService.insertBatch(performanceLogs);
                }
            }

            // 更新订单数等信息
            if (pcp.getFirstOrderTime() == null) {
                pcp.setFirstOrderTime((int) Duration.between(changeTime, orderTime).toMinutes());
            }
            pcp.setOrderCountAfterChange(pcp.getOrderCountAfterChange() + 1);

            // 更新记录
            pcp.setPerformance(performance);
            pcp.setPerformanceDetail(detail.toString());
            updateById(pcp);
        } catch (Exception e) {
            log.error("[换电绩效] 更新绩效时发生错误, 换电记录id: {}", pcl.getPowerChangeLogId(), e);
        }
    }

    /**
     * 计算换电常规方案绩效
     */
    private void calculateConventionModePerformance(PowerChangeLog pcl, PowerChangePerformance pcp, List<PowerChangePerformanceLog> performanceLogs) {
        PowerChangePerformanceConfig config = ruleGroupService.selectBizPerformanceConfig(pcp.getAccountId(), PowerChangePerformanceConfig::fromRaw, PerformanceBizType.POWER_CHANGE_CONVENTION);
        log.info("[换电绩效] 计算常规方案,换电记录id: {}", pcp.getPowerChangeLogId());

        BigDecimal performance = BigDecimal.ZERO;
        StringBuilder detail = new StringBuilder();

        // 基础绩效
        if (config.getConventionBasic() != null && config.getConventionBasic().getEnabled()) {
            log.info("[换电绩效] 换电记录id: {}, 适用常规方案基础绩效", pcp.getPowerChangeLogId());
            BigDecimal validPerf = config.getConventionBasic().getValidPerformance();
            performance = performance.add(validPerf);
            detail.append("常规方案基础绩效: ")
                    .append(NumberUtil.toStr(validPerf))
                    .append(";");
            PowerChangePerformanceLog performanceLog = new PowerChangePerformanceLog();
            BeanUtil.copyProperties(pcp, performanceLog, "performance", "performanceDetail", "remark");
            performanceLog.setPerformance(validPerf);
            performanceLog.setPerformanceDetail("常规方案基础绩效: " + NumberUtil.toStr(validPerf) + ";");
            performanceLog.setRuleType(PerformanceRuleType.BASIC.getValue());
            performanceLog.setRemark("MAIN-BASIC-常规方案基础");
            performanceLogs.add(performanceLog);
        }

        // 低电优先换电
        if (config.getLowPowerBased() != null && config.getLowPowerBased().getEnabled()) {
            for (LowPowerRule subRule : config.getLowPowerBased().getSubRules()) {
                if (subRule.getBeforeChangePower().match(pcl.getOldSoc())) {
                    log.info("[换电绩效] 换电记录id: {}, 适用低电优先换电绩效, 换电前电量范围: {}", pcp.getPowerChangeLogId(), subRule.getBeforeChangePower());
                    performance = performance.add(subRule.getPerformance());
                    detail.append("低电优先绩效: ")
                            .append(NumberUtil.toStr(subRule.getPerformance()))
                            .append("(电量百分比: ")
                            .append(subRule.getBeforeChangePower())
                            .append(");");
                    PowerChangePerformanceLog performanceLog = new PowerChangePerformanceLog();
                    BeanUtil.copyProperties(pcp, performanceLog, "performance", "performanceDetail", "remark");
                    performanceLog.setPerformance(subRule.getPerformance());
                    performanceLog.setPerformanceDetail("低电优先绩效: " + NumberUtil.toStr(subRule.getPerformance()) + "(电量百分比: " + subRule.getBeforeChangePower() + ");");
                    performanceLog.setRuleType(PerformanceRuleType.LOW_POWER.getValue());
                    performanceLog.setRemark("MAIN-LOW_POWER-低电优先");
                    performanceLogs.add(performanceLog);
                    break;
                }
            }
        }

        // 换电后可用电量
        if (config.getPowerAfterChangeBased() != null && config.getPowerAfterChangeBased().getEnabled()) {
            for (PowerAfterChangeRule subRule : config.getPowerAfterChangeBased().getSubRules()) {
                if (subRule.getAfterChangePower().match(pcl.getNewSoc())) {
                    log.info("[换电绩效] 换电记录id: {}, 适用换电后可用电量绩效, 换电后电量范围: {}", pcp.getPowerChangeLogId(), subRule.getAfterChangePower());
                    performance = performance.add(subRule.getPerformance());
                    detail.append("换电后可用电量绩效: ")
                            .append(NumberUtil.toStr(subRule.getPerformance()))
                            .append("(电量百分比: ")
                            .append(subRule.getAfterChangePower())
                            .append(");");
                    PowerChangePerformanceLog performanceLog = new PowerChangePerformanceLog();
                    BeanUtil.copyProperties(pcp, performanceLog, "performance", "performanceDetail", "remark");
                    performanceLog.setPerformance(subRule.getPerformance());
                    performanceLog.setPerformanceDetail("换电后可用电量绩效: " + NumberUtil.toStr(subRule.getPerformance()) + "(电量百分比: " + subRule.getAfterChangePower() + ");");
                    performanceLog.setRuleType(PerformanceRuleType.POWER_AFTER_CHANGE.getValue());
                    performanceLog.setRemark("MAIN-POWER_AFTER_CHANGE-换电后可用电量");
                    performanceLogs.add(performanceLog);
                    break;
                }
            }
        }

        pcp.setPerformance(performance);
        pcp.setPerformanceDetail(detail.toString());
    }

    /**
     * 计算换电站点优先方案绩效
     */
    private void calculateStationModePerformance(PowerChangePerformance pcp, List<PowerChangePerformanceLog> performanceLogs) {
        PowerChangePerformanceConfig config = ruleGroupService.selectBizPerformanceConfig(pcp.getAccountId(), PowerChangePerformanceConfig::fromRaw, PerformanceBizType.POWER_CHANGE_STATION);
        log.info("[换电绩效] 计算站点优先方案,换电记录id: {}", pcp.getPowerChangeLogId());

        BigDecimal performance = BigDecimal.ZERO;
        StringBuilder detail = new StringBuilder();

        // 基础绩效
        if (config.getStationBasic() != null && config.getStationBasic().getEnabled()) {
            log.info("[换电绩效] 换电记录id: {}, 适用站点优先方案基础绩效", pcp.getPowerChangeLogId());
            BigDecimal validPerf = config.getStationBasic().getValidPerformance();
            performance = performance.add(validPerf);
            detail.append("站点优先方案基础绩效: ")
                    .append(NumberUtil.toStr(validPerf))
                    .append(";");
            PowerChangePerformanceLog performanceLog = new PowerChangePerformanceLog();
            BeanUtil.copyProperties(pcp, performanceLog, "performance", "performanceDetail", "remark");
            performanceLog.setPerformance(validPerf);
            performanceLog.setPerformanceDetail("站点优先方案基础绩效: " + NumberUtil.toStr(validPerf) + ";");
            performanceLog.setRuleType(PerformanceRuleType.BASIC.getValue());
            performanceLog.setRemark("MAIN-BASIC-站点优先方案");
            performanceLogs.add(performanceLog);
        }

        // 站点优先级
        sp:
        if (config.getStationPriorityBased() != null && config.getStationPriorityBased().getEnabled() && pcp.getParkId() != null) {
            ParkPoint parkPoint = parkPointService.getByParkPointId(pcp.getParkId());
            if (parkPoint == null) {
                break sp;
            }

            for (StationPriorityBasedRule subRule : config.getStationPriorityBased().getSubRules()) {
                if (Objects.equals(parkPoint.getLevel(), subRule.getLevel())) {
                    log.info("[换电绩效] 换电记录id: {}, 适用站点优先级绩效, 站点名称: {}, 优先级: {}", pcp.getPowerChangeLogId(), parkPoint.getName(), parseParkPointLevel(parkPoint.getLevel()));
                    performance = performance.add(subRule.getPerformance());
                    detail.append("站点优先级绩效: ")
                            .append(NumberUtil.toStr(subRule.getPerformance()))
                            .append("(")
                            .append(parseParkPointLevel(parkPoint.getLevel()))
                            .append(");");
                    PowerChangePerformanceLog performanceLog = new PowerChangePerformanceLog();
                    BeanUtil.copyProperties(pcp, performanceLog, "performance", "performanceDetail", "remark");
                    performanceLog.setPerformance(subRule.getPerformance());
                    performanceLog.setPerformanceDetail("站点优先级绩效: " + NumberUtil.toStr(subRule.getPerformance()) + "(" + parseParkPointLevel(parkPoint.getLevel()) + ");");
                    performanceLog.setRuleType(PerformanceRuleType.STATION_PRIORITY.getValue());
                    performanceLog.setRemark("MAIN-STATION_PRIORITY-站点优先级：" + parseParkPointLevel(parkPoint.getLevel()));
                    performanceLogs.add(performanceLog);
                }
            }
        }

        pcp.setPerformance(performance);
        pcp.setPerformanceDetail(detail.toString());
    }

    /**
     * 解析站点等级
     */
    private static String parseParkPointLevel(int level) {
        switch (level) {
            case 1:
                return "热门一级";
            case 2:
                return "热门二级";
            case 3:
                return "普通站点";
            case 4:
                return "冷门二级";
            case 5:
                return "冷门一级";
            default:
                return "未知";
        }
    }

    /**
     * 更新绩效
     *
     * @param performanceId 绩效ID
     * @param performance   绩效值
     * @param remark        备注
     */
    @Transactional("logTransactionManager")
    public void updatePerformance(Long performanceId, BigDecimal performance, String remark) {
        PowerChangePerformance update = getById(performanceId);
        BigDecimal oldPerformance = update.getPerformance();
        update.setPerformance(performance);
        update.setRemark(remark);
        update.setPerformanceDetail("人工修改绩效: 总绩效" + NumberUtil.toStr(performance, true));
        update.setPerformanceType(PerformanceTypeConstant.MANUAL);
        updateById(update);
        // 计算新旧绩效差值，用于新增一条绩效日志记录power_change_performance_log
        BigDecimal subPerformance = performance.subtract(oldPerformance);
        if (subPerformance.compareTo(BigDecimal.ZERO) == 0){
            return;
        }
        // 记录绩效日志  业务类型设置为人工， 绩效为新旧绩效的差值
        PowerChangePerformanceLog log = new PowerChangePerformanceLog();
        BeanUtil.copyProperties(update, log, "remark");
        log.setPerformance(subPerformance);
        log.setRuleType(PerformanceRuleType.MANUAL.getValue());
        log.setRemark("MAIN-人工修改绩效: " + NumberUtil.toStr(oldPerformance, true)+" -> "+ NumberUtil.toStr(performance, true));
        performanceLogService.save(log);
    }

    /**
     * @description: 根据设置的当前用户的运维权限获取绩效数据
     * @author: mo.shanyong
     * @date: 2025/5/12 11:13
     * @param: req
     * @param: loginAccountUser
     * @return: java.util.List<com.tbit.main.pojo.maintain_performance.stat.PerformanceOverviewResp>
     */
    private List<PerformanceOverviewResp> getPerformanceList(PerformanceOverviewReq req,AccountUser loginAccountUser){
        //数据权限（0全部，1仅自己）
        req.setAccountUserId(Objects.equals(loginAccountUser.getRole().getDataPermission(),1) ? loginAccountUser.getAccountUserId() : null);
        return getBaseMapper().queryOverviewPage(req);
    }

}
